package hyj.qx.websocket.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hyj.qx.websocket.entity.User;
import hyj.qx.websocket.mapper.UserMapper;
import hyj.qx.websocket.service.UserService;
import hyj.qx.websocket.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Integer add(User user) {
        if(user ==null){
            throw new RuntimeException("用户实体不能为空");
        }
        // 返回插入数据库的数量
        int insert = userMapper.insert(user);
        // 判断插入数量>0,表示插入成功;
        if(insert>0){
            // 返回插入的用户id
            return user.getId();
        }
        throw new RuntimeException("新增用户失败");
    }

    @Override
    public Integer deleteOne(String userId) {
       int delete = userMapper.deleteById(userId);
       if(delete>0){
           return delete;
       }
       throw new RuntimeException("\"删除用户失败! id: \"+userId");
    }

    @Override
    public User updetByUserId(User user) {
        if(user==null){
            throw new RuntimeException("用户信息为空,更新失败");
        }
        int update = userMapper.updateById(user);
        if(update>0){
            return  user;
        }
        throw new RuntimeException("用户更新失败");
    }

    @Override
    public User selectUser(String userId) {
        // 验证用户id不能为空字符串
        if(StrUtil.isBlank(userId)){
            throw new RuntimeException("用户id不能为空");
        }
        return userMapper.selectById(userId);
    }

    @Override
    public PageVo<User> page(String userName, int pageNumber, int pageSize) {
        // 创建查询条件包装器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 判断包含用户名称查询条件, 将查询条件添加到queryWrapper里
        if(StrUtil.isNotBlank(userName)){
            // 添加模糊查询用户名条件
            queryWrapper.like("user_name",userName);
        }
        // 构建分页查询参数
        IPage<User> pageParam= new Page<>(pageNumber,pageSize);
        // 执行分页查询
        IPage<User> userIPage = userMapper.selectPage(pageParam, queryWrapper);
        // 返回分页结果
        return  new PageVo<>(userIPage);
    }
}
